package com.fzkj.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @ description  求和
 * @ author yaya
 * @ since 2024/9/5
 */
public class URecursiveTask extends RecursiveTask<Long> {

    /**
     * 拆分的临界值
     */
    private static final long THRESHOLD = 3000L;

    /**
     * 起始值
     */
    private final long start;

    /**
     * 结束值
     */
    private final long end;

    public URecursiveTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        // 如果拆分后的值小于三千
        if (length <= THRESHOLD) {
            // 任务不用再拆分了.可以计算了
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            System.out.println("计算: " + start + " -> " + end + ",结果为: " + sum);
            return sum;
        } else {
            // 数量大于预定的数量,任务还需要再拆分
            long middle = (start + end) / 2;
            System.out.println("拆分: 左边 " + start + " -> " + middle + ", 右边 " + (middle + 1) + " -> " + end);
            // 左边的变量
            URecursiveTask left = new URecursiveTask(start, middle);
            // 表示新开了一个任务
            left.fork();
            URecursiveTask right = new URecursiveTask(middle + 1, end);
            right.fork();
            return left.join() + right.join();
        }
    }
}
